/**
 * 路由权限检查工具
 * 参照原项目的权限控制逻辑
 */

import type { RouteRecordRaw } from 'vue-router';
import { useAuthStore } from '@/store/modules/auth';

/**
 * 检查路由是否有权限访问
 * @param route 路由配置
 * @returns 是否有权限访问
 */
export function hasAuth(route: RouteRecordRaw): boolean {
  const authStore = useAuthStore();
  const userInfo = authStore.userInfo;
  
  // 如果用户信息不完整，返回false（除了常量路由）
  if (!userInfo.userId && !route.meta?.constant) {
    return false;
  }
  
  // 超级管理员（identity === 1）拥有所有权限
  if (userInfo.identity === 1) {
    return true;
  }
  
  // 检查menuId权限（这是核心权限控制）
  if (route.meta?.menuId) {
    const menuId = route.meta.menuId as number;
    
    // 获取用户权限数组
    const userRights = userInfo.rights as number[] || [];
    
    // 检查用户权限数组中是否包含该menuId
    return userRights.includes(menuId);
  }
  
  // 如果没有menuId但有roles配置，检查角色权限
  if (route.meta?.roles) {
    const roles = route.meta.roles as string[];
    return roles.some(role => userInfo.roles?.includes(role));
  }
  
  // 对于没有权限配置的路由（如首页、常量路由等），默认允许访问
  return true;
}

/**
 * 递归过滤有权限的路由
 * @param routes 路由数组
 * @returns 过滤后的路由数组
 */
export function filterAuthRoutes(routes: RouteRecordRaw[]): RouteRecordRaw[] {
  const filteredRoutes: RouteRecordRaw[] = [];
  
  for (const route of routes) {
    if (hasAuth(route)) {
      const filteredRoute = { ...route };
      
      // 递归处理子路由
      if (route.children && route.children.length > 0) {
        filteredRoute.children = filterAuthRoutes(route.children);
      }
      
      filteredRoutes.push(filteredRoute);
    }
  }
  
  return filteredRoutes;
}

/**
 * 检查用户是否拥有特定的业务权限
 * @param permission 权限标识，如 'good.view', 'category.modify'
 * @returns 是否有权限
 */
export function hasBusinessPermission(permission: string): boolean {
  const authStore = useAuthStore();
  const rights = authStore.getInventoryRights();
  
  if (!rights) return false;
  
  const [module, action] = permission.split('.');
  
  switch (module) {
    case 'good':
      return rights.good?.[action as keyof typeof rights.good] !== false;
    case 'category':
      return rights.category?.[action as keyof typeof rights.category] !== false;
    case 'custom':
      return rights.custom?.[action as keyof typeof rights.custom] !== false;
    case 'stock':
      return rights.stock?.[action as keyof typeof rights.stock] !== false;
    default:
      return false;
  }
}